/*************************************************
 Copyright (c) 2019
 All rights reserved.
 File name:     dlt645_port.c
 Description:   DLT645 移植&使用例程文件
 History:
 1. Version:    
    Date:       2019-09-19
    Author:     wangjunjie
    Modify:     
*************************************************/
#include "dlt645.h"
#include <stdlib.h>
#include <stdio.h>


//FILE* gFileReadDLT645Data;
FILE* gFileWriteDLT645Data;
unsigned char gDltDataIndex = 0;
unsigned char gDlt645[4][128] =
{
    {19,0x68, 0x16, 0x06, 0x00, 0x06, 0x20, 0x20, 0x68, 0x91, 0x07, 0x33, 0x33, 0x36, 0x35, 0x49, 0x35, 0x33, 0x4C, 0x16},//瞬时总有功功率,00.0216,02030000 19
    {19,0x68, 0x16, 0x06, 0x00, 0x06, 0x20, 0x20, 0x68, 0x91, 0x07, 0x33, 0x34, 0x35, 0x35, 0xCB, 0x34, 0x33, 0xCD, 0x16},//A相电流000.198,02020100, 0x	19
    {18,0x68, 0x16, 0x06, 0x00, 0x06, 0x20, 0x20, 0x68, 0x91, 0x06, 0x33, 0x34, 0x34, 0x35, 0x3C, 0x56, 0x2B, 0x16},//A相电压230.9,02010100 18
    {18,0x68, 0x16, 0x06, 0x00, 0x06, 0x20, 0x20, 0x68, 0x91, 0x06, 0x33, 0x33, 0x39, 0x35, 0x5B, 0x37, 0x2F, 0x16}//总功率因数0.428,02060000 18
};

/**
 * Name:    dlt645_hw_read
 * Brief:   dlt645 硬件层接收数据
 * Input:
 *  @ctx:   645运行环境
 *  @msg:   接收数据存放地址
 *  @len:   数据最大接收长度 
 * Output:  读取数据的长度
 */
static int dlt645_hw_read(dlt645_t *ctx, uint8_t *msg ,uint16_t len)
{
    //实际接收长度
    int read_len = 0;
    int i = 0;

    
    read_len = gDlt645[gDltDataIndex][0];
    memcpy(msg, &(gDlt645[gDltDataIndex][1]), read_len);



    printf("\r\nAmmeter Recevive:");
    fprintf(gFileWriteDLT645Data, "\r\nAmmeter Recevive:");
    for (i = 0; i < read_len; i++)
    {
        printf("%02x ", msg[i]);
        fprintf(gFileWriteDLT645Data, "%02x ", msg[i]);
    }

    printf("\r\n");
    fprintf(gFileWriteDLT645Data, "\r\n");

    gDltDataIndex++;
    gDltDataIndex = gDltDataIndex % 4;

    return read_len;
}

/**
 * Name:    dlt645_hw_write
 * Brief:   dlt645 硬件层发送数据
 * Input:
 *  @ctx:   645运行环境
 *  @buf:   待发送数据
 *  @len:   发送长度
 * Output:  实际发送的字节数，错误返回-1
 */
static int dlt645_hw_write(dlt645_t *ctx, uint8_t *buf, uint16_t len)
{
    int i = 0;
    

    printf("\r\nAmmeter Send    :");
    fprintf(gFileWriteDLT645Data, "\r\nAmmeter Send    :");
    for (i = 0; i < len; i++)
    {
        printf("%02x ", buf[i]);
        fprintf(gFileWriteDLT645Data, "%02x ", buf[i]);
    }
    
    printf("\r\n");
    fprintf(gFileWriteDLT645Data, "\r\n");

    return len;
}


/**
 * Name:    dlt645_port_init
 * Brief:   645采集硬件层初始化
 * Input:   None
 * Output:  None
 */
int dlt645_port_init(void)
{
    //gFileReadDLT645Data = fopen("dlt_data.dat", "r");
    gFileWriteDLT645Data = fopen("dlt_analysis.txt", "w");
    gDltDataIndex = 0;


    return  0;
}

//645结构体注册
dlt645_t dlt645 = {
    {0},
    0,
    dlt645_hw_write,
    dlt645_hw_read,
    0
};
